﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnonymousTypesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            NorthWindClassesDataContext db = new NorthWindClassesDataContext();

            // 在Select子句，声明了一个匿名类型
            var products = from p in db.Products
                           where p.UnitPrice > 99
                           select new
                           {
                               ID = p.ProductID,
                               Name = p.ProductName,
                               UnitPrice = p.UnitPrice,
                               TotalRevenue = p.Order_Details.Sum(o => o.UnitPrice * o.Quantity),
                           };

            foreach (var product in products)
            {
                // var句法给了动态语言一样的灵活性，还保留了强类型语言的好处
                // Notice： product.Name 是 Intellisense
                Console.WriteLine(product.Name);
            }

            //////////////////////////////////
            // 使用匿名类型做分层构形
            /////////////////////////////////
            var reorderQuery = from p in db.Products
                               where p.UnitPrice > 50
                               group p by p.ReorderLevel into reorderGroups
                               select reorderGroups;
            
            foreach (var stockGroup in reorderQuery)
            {
                Console.WriteLine("Reorder Stock Level" + stockGroup.Key);

                foreach (var product in stockGroup)
                {
                    Console.WriteLine("..." + product.ProductName);
                }
            }

            //////////////////////////////////
            // 使用匿名类型做分层构形
            /////////////////////////////////
            var specialProducts = from p in db.Products
                                  where p.UnitPrice > 50
                                  select new
                                  {
                                      Id = p.ProductID,
                                      Name = p.ProductName,
                                      LastFiveOrders = p.Order_Details.Take(5)
                                  };
            
            foreach (var product in specialProducts)
            {
                Console.WriteLine(product.Name);

                foreach (var order in product.LastFiveOrders)
                {
                    Console.WriteLine(order.Quantity);
                }
            }
        }
    }
}
